package com.eastmoney.emis.edda.infrastructure.eddi.repository;

import com.eastmoney.emis.edda.domain.entity.EddiInstruction;
import com.eastmoney.emis.edda.domain.repository.HsbcEddiRepository;
import com.eastmoney.emis.edda.infrastructure.eddi.mapper.EmhkBankTrademidMapper;
import com.eastmoney.emis.edda.infrastructure.eddi.po.EmhkBankTrademidPo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: Description
 * @projectName: EDDA-HSBC
 * @package: com.eastmoney.emis.edda.domain.repository
 * @author: 汪程程
 * @date: 2022/9/29 5:52 PM
 * @version: 1.0
 */
@Repository
public class HsbcEddiRepositoryImpl implements HsbcEddiRepository {


    @Autowired
    private EmhkBankTrademidMapper trademidHsbcMapper;


    @Override
    public void saveDebitInstruction(EddiInstruction eddiInstruction) {
        if(eddiInstruction.getEid() == null) {
            addDebitInstruction(eddiInstruction);
            return;
        }
        updateDebitInstruction(eddiInstruction);
    }

    @Override
    public void addDebitInstruction(EddiInstruction eddiInstruction) {
        eddiInstruction.setEid(trademidHsbcMapper.getEid(eddiInstruction.getClientId()));
        trademidHsbcMapper.addEmhkBankTrademid(eddiInstruction.getClientId(), new EmhkBankTrademidPo(eddiInstruction));
    }

    @Override
    public void updateDebitInstruction(EddiInstruction eddiInstruction) {
        trademidHsbcMapper.updateEmhkBankTrademid(eddiInstruction.getClientId(), new EmhkBankTrademidPo(eddiInstruction));
    }

    @Override
    public void updateMandateId(EddiInstruction eddiInstruction) {
        trademidHsbcMapper.updateMandateId(eddiInstruction.getClientId(), eddiInstruction.getEid(), eddiInstruction.getMandateId());
    }

    @Override
    public EddiInstruction findEddiByEid(String eid) {
        EmhkBankTrademidPo trademidPo = trademidHsbcMapper.findByEid(eid);
        return trademidPo == null ? null : new EddiInstruction(trademidPo);
    }

    @Override
    public List<EddiInstruction> findAllUncompletedByEITime(Date date) {
        return trademidHsbcMapper.findAllUnCompletedByEITime(date).stream().map(EddiInstruction::new).collect(Collectors.toList());
    }
}
